<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/myblog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/myblog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/myblog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/myblog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/myblog/css/main.css">


<link rel="stylesheet" href="/myblog/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/myblog/lib/pace/pace-theme-minimal.min.css">
  <script src="/myblog/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gao-qianwei.gitee.io","root":"/myblog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="一、简介    类模板和函数模板的定义及使用类似。有时，有两个或多个类，其功能是相同的，仅仅是数据类型不同。">
<meta property="og:type" content="article">
<meta property="og:title" content="类模板">
<meta property="og:url" content="https://gao-qianwei.gitee.io/myblog/2021/05/07/C++%E6%B3%9B%E5%9E%8B%EF%BC%9A%E7%B1%BB%E6%A8%A1%E6%9D%BF/index.html">
<meta property="og:site_name" content="学无止境">
<meta property="og:description" content="一、简介    类模板和函数模板的定义及使用类似。有时，有两个或多个类，其功能是相同的，仅仅是数据类型不同。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-05-07T13:33:44.684Z">
<meta property="article:modified_time" content="2021-05-07T13:33:00.270Z">
<meta property="article:author" content="高乾威">
<meta property="article:tag" content="C++">
<meta property="article:tag" content="泛型">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://gao-qianwei.gitee.io/myblog/2021/05/07/C++%E6%B3%9B%E5%9E%8B%EF%BC%9A%E7%B1%BB%E6%A8%A1%E6%9D%BF/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>类模板 | 学无止境</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/myblog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">学无止境</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/myblog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/myblog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/myblog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/myblog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/myblog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-links">

    <a href="/myblog/links/" rel="section"><i class="fa fa-link fa-fw"></i>友链</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gao-qianwei.gitee.io/myblog/2021/05/07/C++%E6%B3%9B%E5%9E%8B%EF%BC%9A%E7%B1%BB%E6%A8%A1%E6%9D%BF/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/myblog/images/avatar.png">
      <meta itemprop="name" content="高乾威">
      <meta itemprop="description" content="报我楼成秋望月，把君诗读夜回灯">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          类模板
        </h1>

        <div class="post-meta">

          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-05-07 21:33:44 / 修改时间：21:33:00" itemprop="dateCreated datePublished" datetime="2021-05-07T21:33:44+08:00">2021-05-07</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblog/categories/C/" itemprop="url" rel="index"><span itemprop="name">C++</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblog/categories/C/%E6%B3%9B%E5%9E%8B/" itemprop="url" rel="index"><span itemprop="name">泛型</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
            <span class="post-meta-divider">|</span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="一、简介"><a href="#一、简介" class="headerlink" title="一、简介"></a>一、简介</h3><p>    类模板和函数模板的定义及使用类似。有时，有两个或多个类，其功能是相同的，仅仅是数据类型不同。</p>
<span id="more"></span>

<ul>
<li>类模板用于实现类所需数据的类型参数化</li>
<li>类模板在表示如数组、表、图等数据结构显得特别重要，这些数据结构的表示和算法不受所包含的数据类型的影响。</li>
</ul>
<h3 id="二、语法"><a href="#二、语法" class="headerlink" title="二、语法"></a>二、语法</h3><p>    C++ 中类模板的写法如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;类型参数表&gt;</span><br><span class="line"><span class="class"><span class="keyword">class</span> 类模板名&#123;</span></span><br><span class="line">  成员函数和成员变量</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>    类型参数表的写法如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span>类塑参数1, <span class="keyword">class</span>类型参数2, ...</span></span><br></pre></td></tr></table></figure>

<p>    类模板中的成员函数放到类模板定义外面写时的语法如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;类型参数表&gt;</span><br><span class="line">返回值类型 类模板名&lt;类型参数名列表&gt;::成员函数名(参数表)</span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>    用类模板定义对象的写法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">类模板名&lt;真实类型参数表&gt; 对象名(构造函数实际参数表);</span><br></pre></td></tr></table></figure>

<p>    如果类模板有无参构造函数，那么也可以使用如下写法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">类模板名 &lt;真实类型参数表&gt; 对象名;</span><br></pre></td></tr></table></figure>

<p>    例：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="built_in">Person</span>(T id,T age)&#123;</span><br><span class="line">		<span class="keyword">this</span>-&gt;mAge = age;</span><br><span class="line">		<span class="keyword">this</span>-&gt;mId = id;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">Show</span><span class="params">()</span></span>&#123;	</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;ID:&quot;</span> &lt;&lt; mId &lt;&lt; <span class="string">&quot; Age:&quot;</span> &lt;&lt; mAge &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	T mId;</span><br><span class="line">	T mAge;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">()</span></span>&#123;	</span><br><span class="line">	<span class="comment">//函数模板在调用的时候，可以自动类型推导</span></span><br><span class="line">	<span class="comment">//类模板必须显式指定类型</span></span><br><span class="line">	<span class="function">Person&lt;<span class="keyword">int</span>&gt; <span class="title">p</span><span class="params">(<span class="number">15</span>,<span class="number">22</span>)</span></span>;</span><br><span class="line">	p.<span class="built_in">Show</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="三、类模板的派生"><a href="#三、类模板的派生" class="headerlink" title="三、类模板的派生"></a>三、类模板的派生</h3><ol>
<li>普通类派生类模板</li>
<li>类模板也可以派生类模板，这时，派生类模板的参数表中应包含基类模板的参数。</li>
<li>模板类与普通类一样也具有多继承，即模板类之间允许有多继承。</li>
</ol>
<p>     可以从类模板派生出新的类，既可以派生类模板，也可以派生非模板类。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//类模板派生普通类</span></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="built_in">Person</span>()&#123;</span><br><span class="line">		mAge = <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	T mAge;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//类区定义对象，这个对象需要编译分配内存,要指定类型</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SubPerson</span> :</span> <span class="keyword">public</span> Person&lt;<span class="keyword">int</span>&gt;&#123;&#125;;</span><br></pre></td></tr></table></figure>

<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//类模板派生类模板</span></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">J</span><span class="params">()</span></span>&#123;</span><br><span class="line">		cout &lt;&lt; mAge &lt;&lt; <span class="string">&quot;动物在叫!&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	T mAge;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Cat</span> :</span> <span class="keyword">public</span> Animal&lt;T&gt;&#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;	</span><br><span class="line">	Cat&lt;<span class="keyword">int</span>&gt; cat;<span class="comment">//指定类型</span></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="四、类模板外部实现成员函数"><a href="#四、类模板外部实现成员函数" class="headerlink" title="四、类模板外部实现成员函数"></a>四、类模板外部实现成员函数</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="built_in">Person</span>(T age, T id);</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">Show</span><span class="params">()</span></span>;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	T mAge;</span><br><span class="line">	T mID;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//外部实现函数</span></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line">Person&lt;T&gt;::<span class="built_in">Person</span>(T age, T id)&#123;</span><br><span class="line">	<span class="keyword">this</span>-&gt;mID = id;</span><br><span class="line">	<span class="keyword">this</span>-&gt;mAge = age;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="keyword">void</span> Person&lt;T&gt;::<span class="built_in">Show</span>()&#123;</span><br><span class="line">	cout &lt;&lt; <span class="string">&quot;Age:&quot;</span> &lt;&lt; mAge &lt;&lt; <span class="string">&quot; ID:&quot;</span> &lt;&lt; mID &lt;&lt; endl;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="五、类模板的编译"><a href="#五、类模板的编译" class="headerlink" title="五、类模板的编译"></a>五、类模板的编译</h3><p>    首先，一个<em>编译单元</em>（<em>translation unit</em>）是指一个*.cpp<em>文件以及它所</em>#include<em>的所有</em>.h<em>文件，</em>.h<em>文件里的代码将会被扩展到包含它的</em>.cpp<em>文件里，然后编译器编译该</em>.cpp<em>文件为一个</em>.obj<em>文件（假定我们的平台是win32），后者拥有</em>PE<em>（</em>Portable Executable<em>，即</em>windows<em>可执行文件）文件格式，并且本身包含的就已经是二进制码，但是不一定能够执行，因为并不保证其中一定有</em>main<em>函数。当编译器将一个工程里的所有</em>.cpp<em>文件以分离的方式编译完毕后，再由连接器（</em>linker<em>）进行连接成为一个</em>.exe*文件。</p>
<p>    就像类一样，类模板是可以将其实现与声明放在一起的，或者也可以将接口与实现分离。但是呢，编译器由于历史原因对于分离式编译的支持非常弱，并且因平台的不同支持力度有所不同。</p>
<p>    STL 的类模板都是接口与实现放在一起的，随着主流走就可以。（文件保存为<em><strong>类模板.hpp</strong></em>,其实质就是将.cpp的实现代码混入.h头文件当中，定义与实现都包含在同一文件，则该类的调用者只需要include该hpp文件即可，无需再 将cpp加入到project中进行编译。）</p>
<h3 id="六、类模板中的static关键字"><a href="#六、类模板中的static关键字" class="headerlink" title="六、类模板中的static关键字"></a>六、类模板中的<strong>static</strong>关键字</h3><p>    不同的类型参数的类的静态成员变量是相互独立的，这是由类模板的实现机制决定的。</p>
<figure class="highlight hpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">define</span> _CRT_SECURE_NO_WARNINGS</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="keyword">static</span> <span class="keyword">int</span> a;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span> <span class="keyword">int</span> Person&lt;T&gt;::a = <span class="number">0</span>;<span class="comment">//类外初始化</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	Person&lt;<span class="keyword">int</span>&gt; p1, p2, p3;</span><br><span class="line">	Person&lt;<span class="keyword">char</span>&gt; pp1, pp2, pp3;</span><br><span class="line">	p1.a = <span class="number">10</span>;</span><br><span class="line">	pp1.a = <span class="number">100</span>;</span><br><span class="line">	cout &lt;&lt; p1.a &lt;&lt; <span class="string">&quot; &quot;</span> &lt;&lt; p2.a &lt;&lt; <span class="string">&quot; &quot;</span> &lt;&lt; p3.a &lt;&lt; endl;<span class="comment">//输出10 10 10</span></span><br><span class="line">	cout &lt;&lt; pp1.a &lt;&lt; <span class="string">&quot; &quot;</span> &lt;&lt; pp2.a &lt;&lt; <span class="string">&quot; &quot;</span> &lt;&lt; pp3.a &lt;&lt; endl;<span class="comment">//输出100 100 100</span></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>    可以看到相同类型如int对应的类模板的对象之间的static成员是共享的，不同类型之间如int,float,char对应的类模板的对象之间的static是不共享的。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/myblog/tags/C/" rel="tag"># C++</a>
              <a href="/myblog/tags/%E6%B3%9B%E5%9E%8B/" rel="tag"># 泛型</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/myblog/2021/05/07/C++%E6%B3%9B%E5%9E%8B%EF%BC%9A%E5%87%BD%E6%95%B0%E6%A8%A1%E6%9D%BF/" rel="prev" title="函数模板">
      <i class="fa fa-chevron-left"></i> 函数模板
    </a></div>
      <div class="post-nav-item">
    <a href="/myblog/2021/05/07/STL%EF%BC%9Adeque%E5%AE%B9%E5%99%A8/" rel="next" title="STL_deque容器">
      STL_deque容器 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E7%AE%80%E4%BB%8B"><span class="nav-text">一、简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E8%AF%AD%E6%B3%95"><span class="nav-text">二、语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E7%B1%BB%E6%A8%A1%E6%9D%BF%E7%9A%84%E6%B4%BE%E7%94%9F"><span class="nav-text">三、类模板的派生</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9B%9B%E3%80%81%E7%B1%BB%E6%A8%A1%E6%9D%BF%E5%A4%96%E9%83%A8%E5%AE%9E%E7%8E%B0%E6%88%90%E5%91%98%E5%87%BD%E6%95%B0"><span class="nav-text">四、类模板外部实现成员函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%94%E3%80%81%E7%B1%BB%E6%A8%A1%E6%9D%BF%E7%9A%84%E7%BC%96%E8%AF%91"><span class="nav-text">五、类模板的编译</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%AD%E3%80%81%E7%B1%BB%E6%A8%A1%E6%9D%BF%E4%B8%AD%E7%9A%84static%E5%85%B3%E9%94%AE%E5%AD%97"><span class="nav-text">六、类模板中的static关键字</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="高乾威"
      src="/myblog/images/avatar.png">
  <p class="site-author-name" itemprop="name">高乾威</p>
  <div class="site-description" itemprop="description">报我楼成秋望月，把君诗读夜回灯</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/myblog/archives/">
        
          <span class="site-state-item-count">91</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/myblog/categories/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/myblog/tags/">
          
        <span class="site-state-item-count">59</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="http://github.com/GaoQianwei" title="GitHub → http:&#x2F;&#x2F;github.com&#x2F;GaoQianwei" rel="noopener" target="_blank">GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:2966807184@qq.com" title="E-Mail → mailto:2966807184@qq.com" rel="noopener" target="_blank">E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.zhihu.com/people/xue-wu-zhi-jing-75-22" title="知乎 → https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;xue-wu-zhi-jing-75-22" rel="noopener" target="_blank">知乎</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/weixin_45341339" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;weixin_45341339" rel="noopener" target="_blank">CSDN</a>
      </span>
  </div>



      </div><div>
  <canvas id="canvasDiyBlock" style="width:60%;">当前浏览器不支持canvas，请更换浏览器后再试</canvas>
<script src="/myblog/js/custom/clock.js"></script>

</div>


    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2021-04 到 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">高乾威</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

<span class="post-meta-divider">|</span>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">全站共 117.2k 字</span>
</div>

<span class="post-meta-divider">|</span>
        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/myblog/lib/anime.min.js"></script>
  <script src="/myblog/lib/velocity/velocity.min.js"></script>
  <script src="/myblog/lib/velocity/velocity.ui.min.js"></script>

<script src="/myblog/js/utils.js"></script>

<script src="/myblog/js/motion.js"></script>


<script src="/myblog/js/schemes/pisces.js"></script>


<script src="/myblog/js/next-boot.js"></script>


  <script defer src="/myblog/lib/three/three.min.js"></script>
    <script defer src="/myblog/lib/three/canvas_lines.min.js"></script>


  




  
<script src="/myblog/js/local-search.js"></script>













  

  

</body>
</html>
